package com.cdp.zwy.zwy_manager_back_v1.service;

import com.cdp.zwy.zwy_manager_back_v1.entity.Admin;
import com.cdp.zwy.zwy_manager_back_v1.entity.Employee;
import com.cdp.zwy.zwy_manager_back_v1.mapper.AdminMapper;
import com.cdp.zwy.zwy_manager_back_v1.mapper.EmployeeMapper;
import com.cdp.zwy.zwy_manager_back_v1.service.MyUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public UserDetails loadUserByUsername(String usernameWithRole) throws UsernameNotFoundException {

        // 1. 解析 "角色::用户名" 字符串
        String[] parts = usernameWithRole.split("::");
        if (parts.length != 2) {
            throw new UsernameNotFoundException("用户名格式错误，应为 '角色::用户名'");
        }
        String role = parts[0];
        String username = parts[1];

        // 2. 根据角色查询对应的表
        if ("ADMIN".equals(role)) {
            Admin admin = adminMapper.selectByUsername(username);
            if (admin != null) {
                // 使用自定义的MyUserDetails返回，其中包含了完整的Admin对象
                List<GrantedAuthority> authorities = new ArrayList<>();
                authorities.add(new SimpleGrantedAuthority("ROLE_EMP"));
                authorities.add(new SimpleGrantedAuthority("ROLE_" + admin.getRole()));
                // 添加第二个权限

                return new MyUserDetails(usernameWithRole, admin.getPassword(), authorities, admin);
            }
        } else if ("EMP".equals(role)) {
            Employee employee = employeeMapper.selectByUsername(username);
            if (employee != null) {
                List<GrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority("ROLE_" + employee.getRole()));
                // 返回包含了完整Employee对象的UserDetails
                return new MyUserDetails(usernameWithRole, employee.getPassword(), authorities, employee);
            }
        }

        // 3. 如果找不到用户，抛出异常
        throw new UsernameNotFoundException("在角色 '" + role + "' 下未找到用户: " + username);
    }
}